package com.chen.gulimall.gulimallproduct.service.impl;

import com.chen.gulimall.gulimallproduct.dao.AttrAttrgroupRelationDao;
import com.chen.gulimall.gulimallproduct.dao.AttrGroupDao;
import com.chen.gulimall.gulimallproduct.dao.CategoryDao;
import com.chen.gulimall.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.chen.gulimall.gulimallproduct.entity.AttrGroupEntity;
import com.chen.gulimall.gulimallproduct.entity.CategoryEntity;
import com.chen.gulimall.gulimallproduct.service.CategoryService;
import com.chen.gulimall.gulimallproduct.vo.AttrRespVo;
import com.chen.gulimall.gulimallproduct.vo.AttrVo;
import com.chen.gulimallcommon.common.constant.ProductConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.gulimallcommon.common.utils.PageUtils;
import com.chen.gulimallcommon.common.utils.Query;

import com.chen.gulimall.gulimallproduct.dao.AttrDao;
import com.chen.gulimall.gulimallproduct.entity.AttrEntity;
import com.chen.gulimall.gulimallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);

        this.save(attrEntity);

        //只有当attr为规则属性时才更新关联表
        if (attrEntity.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());

            relationDao.insert(relationEntity);
        }

    }

    //查询对应的attr的信息，包括它属于的组和分类
    @Override
    public PageUtils queryBaseList(Map<String, Object> params, Long catelongId, String type) {

        QueryWrapper<AttrEntity> queryWrapper =  new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrType.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrType.ATTR_YPE_SALE.getCode());

        //如果catelongId为0，则表示查询全部
        if (catelongId != 0) {
            queryWrapper.eq("catelog_id",catelongId);
        }

        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wapper)-> {
                wapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
               queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        //将查询到的list集合中的数据流的方式取出，并且再次进行处理，为其中的分类名和组名属性赋值
        List<AttrEntity> list = page.getRecords();
        list.stream().map((attrEntity) -> {
            //此对象为视图层对象
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);
            //先从关联表中找到该attr对应的组id
            AttrAttrgroupRelationEntity attrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if (attrgroupRelationEntity != null) {
                //只有规则参数才有分组类型，而销售属性只有分类id
                if (attrEntity.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(catelongId);

            if (categoryEntity != null) {
                attrRespVo.setCategoryName(categoryEntity.getName());
            }


            return attrRespVo;
            //最后保存为一个集合
        }).collect(Collectors.toList());

        //重新设置给pageUtils
        pageUtils.setList(list);

        return pageUtils;
    }



    //查找对应的attr所属的paths路径
    @Override
    public AttrRespVo getAttrId(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);

        //此方法就是为attrResponseVo视图层中的属性值赋值完成
        BeanUtils.copyProperties(attrEntity,attrRespVo);

            AttrAttrgroupRelationEntity attrgroupRelationEntity = relationDao.selectById(attrId);
            if (attrgroupRelationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            Long[] catelogPaths = categoryService.findCatelogPath(attrEntity.getCatelogId());

            attrRespVo.setCatelogPath(catelogPaths);

            CategoryEntity categoryEntity = categoryDao.selectById(attrRespVo.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCategoryName(categoryEntity.getName());
            }
        return attrRespVo;
    }


    //修改attr中信息的方法，同时要同步关联表中的信息
    @Transactional
    @Override
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);

        //先更新attr中的信息，在更新关联表中的信息
        this.updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) {
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

            //当count大于0时表示关联表该attr有关联才能更新，否则没有该关联下进行插入操作
            if (count > 0) {
                relationDao.updateById(attrgroupRelationEntity);
            }else {
                relationDao.insert(attrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> list = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        List<Long> attrIds = list.stream().map((attrAttrgroupRelationEntity) -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());

        if (attrIds == null || attrIds.size() == 0) return null;
        return this.listByIds(attrIds);
    }



    @Override
    public PageUtils getAttrNoRelation(Long attrgroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        Long catelogId = attrGroupEntity.getCatelogId();

        List<AttrGroupEntity> list = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));

        List<Long> attrgroupIds = list.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupIds));

        List<Long> attrIds = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId).eq("attr_type",ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());

        if (attrIds == null || attrIds.size() > 0) {
            queryWrapper.notIn("attr_id",attrIds);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectAttrByIds(List<Long> attrIds) {
        return this.baseMapper.selectAttrByIds(attrIds);
    }
}